<template>
  <el-dialog
    title="推荐搭配型号"
    :visible.sync="dialogShow"
    width="80%"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div>
      <search-form
        ref="searchForm"
        :search-config="searchConfig"
        :label-width="100"
        @clear="clearSearch"
        @search="handleSearch"
      />
    </div>
    <el-tabs v-model="activeName" @tab-click="changeTab">
      <el-tab-pane label="全部" name="all">
        <div class="table-list-box">
          <el-table
            ref="multipleTable"
            v-loading="tableLoading"
            :data="tableData"
            border
            height="160"
            header-row-class-name="table-list-header"
            :row-class-name="tableRowClassName"
            tooltip-effect="dark"
            style="width: 100%"
            @row-click="selectRow"
            @select="selectTable"
            @select-all="selectionAll"
            @selection-change="selectChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="modelName" label="搭配型号" min-width="80" show-overflow-tooltip />
            <el-table-column prop="categoryName" label="搭配品类" show-overflow-tooltip />
            <el-table-column prop="seriesName" label="搭配系列" show-overflow-tooltip min-width="120" />
            <el-table-column prop="collocationNum" label="搭配数量" width="80" show-overflow-tooltip />
            <el-table-column prop="recommendModelName" label="对应推荐型号" min-width="100" show-overflow-tooltip />
            <el-table-column prop="recommendCategoryName" label="推荐品类" show-overflow-tooltip />
            <el-table-column prop="recommendSeriesName" label="推荐系列" show-overflow-tooltip min-width="120" />
          </el-table>
        </div>
        <div class="pagination-box">
          <div class="pagination-container">
            <el-pagination
              :current-page.sync="currentPage"
              :page-sizes="pageSizelist"
              :page-size="pageSize"
              layout="sizes, prev, pager, next, slot"
              :total="allTotal === 0 ? total : allTotal"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
              <span class="el-pagination__jump">前往
                <el-input-number
                  v-model="jumpPage"
                  :controls="false"
                  :min="1"
                  @blur="showEnter"
                  @keyup.enter.native="showEnter"
                />页</span>
            </el-pagination>
            <div v-show="total <= pageSize" class="pagination-info">当前显示
              <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
              <span class="total"> {{ tableData.length }} </span> 条记录
            </div>
            <div v-show="total > pageSize" class="pagination-info">当前显示
              <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
              <span :class="[allTotal === 0 && total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ allTotal === 0 && total !== 0 ? total-1 +'+': allTotal }}  </span> 条记录
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="`已选择(${selectedData.length})`" name="selected">
        <div class="table-list-box">
          <el-table
            ref="chosenTable"
            :data="showSelectedData"
            border
            height="160"
            header-row-class-name="table-list-header"
            highlight-current-row
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column prop="modelName" label="搭配型号" width="120" show-overflow-tooltip />
            <el-table-column prop="categoryName" label="搭配品类" show-overflow-tooltip />
            <el-table-column prop="seriesName" label="搭配系列" show-overflow-tooltip width="120" />
            <el-table-column prop="collocationNum" label="搭配数量" width="80" show-overflow-tooltip />
            <el-table-column prop="recommendModelName" label="对应推荐型号" width="120" show-overflow-tooltip />
            <el-table-column prop="recommendCategoryName" label="推荐品类" show-overflow-tooltip />
            <el-table-column prop="recommendSeriesName" label="推荐系列" show-overflow-tooltip width="120" />
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="color:#3dc094; cursor: pointer;"
                  @click="deleteChose(scope.$index,scope.row)"
                >删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- <div style="margin:10px 0;display:inlnk-black;font-size: 14px;">已选择
      <span style="color:#0f3eea;">{{ selectedData.length }}</span>条数据
    </div> -->

    <div slot="footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button type="primary" size="mini" @click="determineChosen">下一步</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getEndProMatch, queryCategoryData } from '@/api/proConfig'
// import { getDictByPatchType } from '@/api/dataDict'
// import { getDictByPatchType } from '@/api/dataDict'
export default {
  name: 'Match',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      activeName: 'all',
      tableLoading: false,
      otherFilter: [],
      recommendProgramList: [],
      seriesNameList: [],
      showSelectedData: [],
      searchConfig: [
        {
          label: '推荐型号',
          prop: 'recommendModelCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `/select-service/api/v1/productModel/page`,
            // paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '推荐型号',
            interfacePath: `/select-service/api/v1/productModel/page`,
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '推荐品类',
          prop: 'recommendCategoryCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `/select-service/api/v1/productCategory/page`,
            // paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '推荐品类',
            interfacePath: `/select-service/api/v1/productCategory/page`,
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '推荐系列',
          prop: 'recommendSeriesCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `/select-service/api/v1/productSaleSeries/page`,
            // paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '推荐系列',
            interfacePath: `/select-service/api/v1/productSaleSeries/page`,
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '搭配型号',
          prop: 'modelCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `/select-service/api/v1/productModel/page`,
            // paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '搭配型号',
            interfacePath: `/select-service/api/v1/productModel/page`,
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '搭配品类',
          prop: 'categoryCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `/select-service/api/v1/productCategory/page`,
            // paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '搭配品类',
            interfacePath: `/select-service/api/v1/productCategory/page`,
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        }
      ],
      pageSize: 5,
      pageSizelist: [5, 10, 15, 20],
      currentPage: 1,
      total: '',
      jumpPage: '',
      allTotal: 0,
      selectedData: [],
      tableData: [],
      formData: {
        seriesName: '',
        seriesCode: '',
        productName: '',
        productRadio: '1',
        productCode: '' // 62323901101 669325001
      },
      modelOtherFilter: []
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.selectedData = []
          this.$nextTick(() => {
            this.$refs.multipleTable.clearSelection()
          })
        }
      }
    }
  },
  async created() {
    // this.otherFilter = this.detailData.otherFilter
    if (this.detailData.lastSelected) {
      this.selectedData = JSON.parse(JSON.stringify(this.detailData.lastSelected))
    }
    const arr = JSON.parse(JSON.stringify(this.detailData.otherFilter))
    const plCodesArr = this.otherFilter.map(item => item.categoryCodes)
    const plCodes = this.removeEqualData(plCodesArr)
    const plDataArr = await this.getCategoryData(plCodes)
    this.otherFilter.forEach(item => {
      plDataArr.forEach(row => {
        if (item.categoryCodes === row.code && row.parentCode) {
          item.categoryCodes = row.parentCode
        }
      })
      // if (item.belongRegion === '软体' || item.belongRegion === 'Q014') {
      //   item.areaCode = 'Q014'
      // }
      // if (item.belongRegion === '套房' || item.belongRegion === 'Q015') {
      //   item.areaCode = 'Q015'
      // }
    })
    const tmpArr = []
    arr.forEach(item => {
      const obj = {
        outpicCategoryNumberId: item.outpicCategoryNumberId,
        areaCode: item.areaCode,
        categoryCodes: item.categoryCodes,
        constCode: this.detailData.constCode,
        seriesCode: item.seriesCode,
        spaceArea: item.spaceTotalArea,
        spaceCode: item.spaceCode,
        styleCode: item.styleCode,
        configDetailDtos: []
      }
      if (item.modelCode) {
        const tmpSelect = {
          categoryCodes: item.categoryCodes,
          modelCode: item.modelCode,
          seriesCode: item.seriesCode,
          styleCode: item.styleCode,
          recommendType: item.recommendType,
          detailCategoryCode: item.detailCategoryCode
        }
        obj.configDetailDtos.push(tmpSelect)
      }
      if (!tmpArr.length) {
        tmpArr.push(obj)
      } else {
        const flag = tmpArr.some(v => v.outpicCategoryNumberId === item.outpicCategoryNumberId)
        if (flag) {
          tmpArr.forEach(m => {
            if (m.outpicCategoryNumberId === item.outpicCategoryNumberId) {
              m.configDetailDtos = [...m.configDetailDtos, ...obj.configDetailDtos]
            }
          })
        } else {
          tmpArr.push(obj)
        }
      }
    })
    this.otherFilter = tmpArr
    this.modelListAll(1, false, JSON.stringify(this.modelOtherFilter))
  },
  mounted() {},
  methods: {
    // // 获取数据字典
    // async getDictByPatchTypeAll(data) {
    //   const obj = await getDictByPatchType(data)
    //     .then(res => {
    //       return res
    //     })
    //   return obj
    // },
    // 格式化数据
    formaterData(arr, dictCode) {
      if (!arr.length) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    removeEqualData(arr) {
      const newArr = []
      for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) === -1) {
          newArr.push(arr[i])
        }
      }
      return newArr
    },
    // 获取品类
    async getCategoryData(arr) {
      const codes = '[' + arr.join(',') + ']'
      const filterRow = [{ 'id': 'code', 'property': 'code', 'operator': 'in', 'value': codes }]
      const dataForm = new FormData()
      dataForm.append('pageFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(filterRow))
      return await queryCategoryData(dataForm).then(res => {
        if (res.success) {
          return res.data.records
        }
      })
    },
    // 清空搜索条件
    clearSearch(data) {
      this.formData.modelCode = ''
      this.formData.categoryCode = ''
      this.formData.seriesCode = ''
      this.formData.recommendProgram = ''
      this.formData.proPosition = ''
      // this.currentPage = 1
      // this.pageSize = 5
      // this.modelListAll()
    },
    // 获取搜索条件
    async handleSearch(data) {
      this.currentPage = 1
      this.pageSize = 5
      const arr = JSON.parse(JSON.stringify(data.filtersRaw))
      if (arr.length) {
        let parentCode = ''
        const plCodeArr = arr.filter(item => item.property === 'categoryCode')
        if (plCodeArr.length) {
          const plCode = [plCodeArr[0].value]
          const pl = await this.getCategoryData(plCode)
          if (pl[0].parentCode) {
            parentCode = pl[0].parentCode
          } else {
            parentCode = pl[0].code
          }
        }
        arr.forEach(item => {
          if (item.property === 'categoryCode') {
            item.value = parentCode
          }
        })
      }
      if (this.activeName === 'all') {
        this.onParams(arr)
      } else {
        if (!this.selectedData.length) return
        if (data.filtersRaw && data.filtersRaw.length) {
          const arr = []
          this.selectedData.forEach(item => {
            const recommendModelList = data.filtersRaw.filter(item => item.property === 'recommendModelCode')
            const recommendPlList = data.filtersRaw.filter(item => item.property === 'recommendCategoryCode')
            const recommendSeriesList = data.filtersRaw.filter(item => item.property === 'recommendSeriesCode')
            const modelList = data.filtersRaw.filter(item => item.property === 'modelCode')
            const categoryList = data.filtersRaw.filter(item => item.property === 'categoryCode')
            let flag1 = true
            let flag2 = true
            let flag3 = true
            let flag4 = true
            let flag5 = true
            if (recommendModelList.length) {
              flag1 = (item.recommendModelCode.search(recommendModelList[0].value) !== -1)
            }
            if (recommendPlList.length) {
              flag2 = (item.recommendCategoryCode.search(recommendPlList[0].value) !== -1)
            }
            if (recommendSeriesList.length) {
              flag3 = (item.recommendSeriesCode.search(recommendSeriesList[0].value) !== -1)
            }
            if (modelList.length) {
              flag4 = (item.modelCode.search(modelList[0].value) !== -1)
            }
            if (categoryList.length) {
              flag5 = (item.categoryCode.search(categoryList[0].value) !== -1)
            }
            if (flag1 && flag2 && flag3 && flag4 && flag5) {
              arr.push(item)
            }
          })
          this.showSelectedData = arr
        } else {
          this.showSelectedData = this.selectedData
        }
      }

      // this.onParams(data)
    },
    modelListAll(currentPage, onlyCountFlag, otherFilters) {
      this.tableLoading = true
      const params = []
      this.otherFilter.forEach(row => {
        const obj = {
          queryCodes: [],
          selectedCodes: []
        }
        row.configDetailDtos.forEach(item => {
          if (item.recommendType === 'RECOMMEND') {
            const queryObj = {
              categoryCode: row.categoryCodes,
              modelCode: item.modelCode,
              seriesCode: row.seriesCode
            }
            obj.queryCodes.push(queryObj)
          }
          // let selectedObj = {}
          // if (item.recommendType === 'MATCH') {
          //   selectedObj = {
          //     categoryCode: item.detailCategoryCode,
          //     modelCode: item.modelCode,
          //     seriesCode: row.seriesCode
          //   }
          // } else {
          const selectedObj = {
            categoryCode: row.categoryCodes,
            modelCode: item.modelCode,
            seriesCode: row.seriesCode
          }
          // }
          // const selectedObj = {
          //   categoryCode: row.categoryCodes,
          //   modelCode: item.modelCode,
          //   seriesCode: row.seriesCode
          // }
          obj.selectedCodes.push(selectedObj)
        })
        params.push(obj)
      })
      console.log('搭配', params)
      // return
      getEndProMatch(params, currentPage, this.pageSize, onlyCountFlag, otherFilters).then(res => {
        if (res.success && res.data && res.data.records) {
          if (!onlyCountFlag) {
            this.tableData = res.data.records
            this.total = res.data.total
            if (this.total <= this.currentPage * this.pageSize) {
              this.allTotal = this.total
            }
            const selectIds = this.selectedData.map(e => {
              return e.id
            })
            // 表格数据对比是否存在已选择数据并对其勾选
            this.tableData.forEach(item => {
              if (selectIds.includes(item.id)) {
                this.$nextTick(() => {
                  this.$refs.multipleTable.toggleRowSelection(item)
                })
              }
            })
          } else {
            this.allTotal = res.data.total
            this.total = res.data.total
            this.currentPage = res.data.page
          }
        }
        this.showSelectedData = this.selectedData
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 去重
    unique(arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.prodModelCode) && res.set(arr.prodModelCode, 1))
    },
    // 确定
    determineChosen() {
      if (!this.selectedData.length) {
        this.$message.warning('请选择搭配型号')
        return
      }
      const equalArr = []
      const tmpSelectList = JSON.parse(JSON.stringify(this.selectedData))
      this.selectedData.forEach((select, sIndex) => {
        tmpSelectList.forEach((t, tindex) => {
          if (sIndex !== tindex && select.recommendModelCode === t.recommendModelCode && select.modelCode === t.modelCode && select.categoryCode === t.categoryCode) {
            equalArr.push(t)
          }
        })
      })
      if (equalArr.length) {
        const arr = this.unique(equalArr)
        arr.forEach(item => {
          item.msg = `型号为${item.modelCode}，品类为${item.categoryCode}，对应推荐型号为${item.recommendModelCode}的数据存在重复现象，请重新选择`
        })
        const msgArr = arr.map(a => a.msg)
        this.$message({
          dangerouslyUseHTMLString: true,
          message: msgArr.join('<br />'),
          type: 'warning'
        })
        return
      }
      const submitArr = []
      const tmpArr = JSON.parse(JSON.stringify(this.detailData.otherFilter))
      tmpArr.forEach(q => {
        const obj = {
          outpicCategoryNumberId: q.outpicCategoryNumberId,
          areaCode: q.areaCode,
          areaName: q.areaName,
          categoryCodes: q.categoryCodes,
          seriesCode: q.seriesCode,
          spaceTotalArea: q.spaceTotalArea,
          spaceCode: q.spaceCode,
          spaceName: q.spaceName,
          styleCode: q.styleCode,
          configDetailDtos: []
        }
        this.selectedData.forEach(item => {
          const finish = {
            checked: false,
            modelCode: item.modelCode,
            modelName: item.modelName,
            detailCategoryCode: item.categoryCode,
            detailCategoryName: item.categoryName,
            detailSeriesCode: item.seriesCode,
            detailSeriesName: item.seriesName,
            // recommendProgram: item.recommendProgram,
            // proPosition: item.proPosition,
            recommendType: 'MATCH'
          }
          if (item.recommendCategoryCode === q.categoryCodes && item.recommendModelCode === q.modelCode) {
            obj.configDetailDtos.push(finish)
          }
        })
        submitArr.push(obj)
      })
      // const uniqueArr = this.unique(submitArr, 'outpicCategoryNumberId')
      const finish = {}
      finish.data = JSON.parse(JSON.stringify(submitArr))
      finish.data.forEach(item => {
        item.recommendType = 'MATCH'
      })
      finish.lastSelected = this.selectedData
      // finish.flag = 'MATCH'
      this.$emit('success', finish)
      this.handleClose()
      this.dialogShow = false
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      this.jumpPage = currentPage
      this.currentPage = currentPage
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.modelListAll(this.currentPage, false, JSON.stringify(this.modelOtherFilter))
    },
    // 分页数据获取---> this.$refs.chosenTable/multipleTable.clearSelection
    handleSizeChange(val) {
      this.pageSize = val
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.jumpToFirstPage()
      this.modelListAll(this.currentPage, false, JSON.stringify(this.modelOtherFilter))
    },
    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage
      const pageRange = `${start}-${end}`
      return pageRange
    },
    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.currentPage
      if (val) {
        page = val
      }
      this.modelListAll(page, true, JSON.stringify(this.modelOtherFilter))
      this.$nextTick(() => {
        this.modelListAll(page, false, JSON.stringify(this.modelOtherFilter))
      })
    },
    setTBIndex({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex
    },
    onParams(data) {
      this.tableLoading = true
      const params = []
      this.otherFilter.forEach(row => {
        const obj = {
          queryCodes: [],
          selectedCodes: []
        }
        row.configDetailDtos.forEach(item => {
          if (item.recommendType === 'RECOMMEND') {
            const queryObj = {
              categoryCode: row.categoryCodes,
              modelCode: item.modelCode,
              seriesCode: row.seriesCode
            }
            obj.queryCodes.push(queryObj)
          }
          const selectedObj = {
            categoryCode: row.categoryCodes,
            modelCode: item.modelCode,
            seriesCode: row.seriesCode
          }
          obj.selectedCodes.push(selectedObj)
        })
        params.push(obj)
      })
      this.modelOtherFilter = data.filter(item =>
        ['modelCode', 'categoryCode', 'seriesCode', 'recommendModelCode', 'recommendCategoryCode', 'recommendSeriesCode'].includes(item.property)
      )
      getEndProMatch(params, 1, this.pageSize, false, JSON.stringify(this.modelOtherFilter)).then(res => {
        if (res.success && res.data && res.data.records) {
          this.tableData = res.data.records
          this.total = res.data.total
          if (this.total <= this.currentPage * this.pageSize) {
            this.allTotal = this.total
          }
          const selectIds = this.selectedData.map(e => {
            return e.id
          })
          // 表格数据对比是否存在已选择数据并对其勾选
          this.tableData.forEach(item => {
            if (selectIds.includes(item.id)) {
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleRowSelection(item)
              })
            }
          })
        }
        this.showSelectedData = this.selectedData
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleClose() {
      this.dialogShow = false
      this.$emit('update:visible', false)
    },
    selectionAll(val) {
      const selectIds = this.selectedData.map(e => {
        return e.id
      })
      val.length &&
        val.forEach(item => {
          if (!selectIds.includes(item.id)) {
            this.selectedData = this.selectedData.concat(item)
          }
        })
      if (!val.length) {
        this.tableData.forEach(item => {
          this.selectedData.forEach((s, index) => {
            if (s.id === item.id) {
              this.selectedData.splice(index, 1)
            }
          })
        })
      }
      this.showSelectedData = this.selectedData
    },
    // 产品数据手动勾选
    selectTable(val, row) {
      if (this.selectedData.length > 0) {
        // 筛选已勾选的code
        const codeList = val.map(e => {
          return e.id
        })
        if (codeList.includes(row.id)) {
          // 判断是勾选还是取消
          this.selectedData = this.selectedData.concat(row)
        } else {
          this.selectedData.forEach((item, index) => {
            if (item.id === row.id) {
              this.selectedData.splice(index, 1)
            }
          })
        }
      } else {
        this.selectedData = val
      }
      this.showSelectedData = this.selectedData
      this.$nextTick(() => {
        this.selectedData.forEach(item => {
          this.$refs.chosenTable.toggleRowSelection(item, true)
        })
      })
    },
    // 产品数据手动勾选
    selectRow(row) {
      if (this.selectedData.length > 0) {
        const arr = JSON.parse(JSON.stringify(this.selectedData))
        // 筛选已勾选的code
        const codeList = arr.map(e => {
          return e.id
        })
        if (!codeList.includes(row.id)) {
          // 判断是勾选还是取消
          this.selectedData = arr.concat(row)
          this.$nextTick(() => {
            this.selectedData.forEach(item => {
              this.$refs.multipleTable.toggleRowSelection(item, true)
            })
          })
        } else {
          this.tableData.forEach(item => {
            if (item.id === row.id) {
              this.$refs.multipleTable.toggleRowSelection(item, false)
            }
          })
          this.$nextTick(() => {
            this.selectedData.forEach((item, index) => {
              if (item.id === row.id) {
                this.selectedData.splice(index, 1)
              }
            })
          })
        }
      } else {
        this.selectedData.push(row)
        this.$nextTick(() => {
          this.selectedData.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        })
      }
      this.showSelectedData = this.selectedData
    },
    deleteChose(index, row) {
      this.selectedData.splice(index, 1)
      this.$nextTick(() => {
        this.tableData.forEach(e => {
          if (e.id === row.id) {
            this.$refs.multipleTable.toggleRowSelection(e, false)
          }
        })
      })
      this.showSelectedData = this.selectedData
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedData.filter(item => row.id === item.id)
      return (filterArr.length > 0) ? 'selected-highlight' : ''
    },
    changeTab(tab) {
      this.$refs.searchForm.handleSearch()
    }
  }
}
</script>

<style scoped lang="scss">

</style>
